package com.gvfish.dao;

import java.util.HashSet;
import java.util.Set;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

import org.springframework.stereotype.Repository;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.gvfish.entity.Authority;
import com.gvfish.entity.Role;
@Repository
public class RoleDao extends CommonDao<Role,Long>{

	private PersistenceManagerFactory persistenceManagerFactory;

	public void setPersistenceManagerFactory(PersistenceManagerFactory pmf) {
		this.persistenceManagerFactory = pmf;
	}
	@Override
	public PersistenceManager getPersistenceManager() {
		return persistenceManagerFactory.getPersistenceManager();
	}
	@Override
	public Class<Role> getTClass() {
		return Role.class;
	}
	public void removeAuth(Long roleId,Long authorityId){
		PersistenceManager pm = getPersistenceManager();
		Key authorityKey = KeyFactory.createKey(Authority.class.getSimpleName(), authorityId);
		try{
			Role role=pm.getObjectById(Role.class, roleId);
			Set<Key> authKeys = role.getAuthorityKeys();
			if(authKeys==null){
				authKeys = new HashSet<Key>();
				role.setAuthorityKeys(authKeys);
			}
			if(authKeys.contains(authorityKey)){
				authKeys.remove(authorityKey);
			}
		}finally{
			pm.close();
		}
	}
	
	public void change(Long roleId,Long authorityId){
		PersistenceManager pm = getPersistenceManager();
		Key authorityKey = KeyFactory.createKey(Authority.class.getSimpleName(), authorityId);
		try{
			Role role=pm.getObjectById(Role.class, roleId);
			Set<Key> authKeys = role.getAuthorityKeys();
			if(authKeys==null){
				authKeys = new HashSet<Key>();
				role.setAuthorityKeys(authKeys);
			}
			if(authKeys.contains(authorityKey)){
				authKeys.remove(authorityKey);
			}else{
				authKeys.add(authorityKey);
				
			}
			
		}finally{
			pm.close();
		}
	}
	
}
